package com.holi.hiteacher.other;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.holi.hiteacher.activity.EmailListAty;
import com.holi.hiteacher.activity.SignInDialogAty;
import com.holi.hiteacher.activity.TestActivity;
import com.holi.hiteacher.bean.EmailBean;
import com.holi.hiteacher.data.DatabaseHelper;
import com.holi.hiteacher.fragment.SchoolInfoFragment;
import com.holi.hiteacher.utils.DataUtils;
import com.j256.ormlite.android.apptools.OpenHelperManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

/**
 * @description:
 * @author: JoshuaWong E-mail:joshuawongchn@gmail.com
 * @date: 2017年01月03日 22:20
 * @version: 1.0
 */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "joshua";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Log.w(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " +
                printBundle(bundle));
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface
                    .EXTRA_MESSAGE));

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.w(TAG, "[MyReceiver] 接收到推送下来的通知");
            processMessage(context, bundle);
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.w(TAG, "[MyReceiver] 用户点击打开了通知");

            // 打开自定义的Activity
            Intent i = new Intent(context, TestActivity.class);
            i.putExtras(bundle);
            i.setFlags(FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(i);
        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.w(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString
                    (JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface
                    .EXTRA_CONNECTION_CHANGE, false);
            Log.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " +
                    connected);
        } else {
            Log.w(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    // 打印所有的 intent extra 数据
    private String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Log.w(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface
                            .EXTRA_EXTRA));
                    Iterator<String> it = json.keys();
                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" + myKey + " - " + json
                                .optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    private static final String TYPE_SIGN_IN_KEY = "type";
    private static final int TYPE_SIGN_IN = 1001;
    private static final int TYPE_EMAIL = 1002;
    private static final String TYPE_EMAIL_FROM_KEY = "from";
    private static final String TYPE_EMAIL_TITLE_KEY = "title";

    //处理自定义信息
    private void processMessage(Context context, Bundle bundle) {
        String content = bundle.getString(JPushInterface.EXTRA_ALERT);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        int msgType = -1;
        String from = "未知", title = "";
        if (!DataUtils.isEmpty(extras)) {
            try {
                JSONObject extraJson = new JSONObject(extras);
                if (extraJson.has(TYPE_SIGN_IN_KEY))
                    msgType = extraJson.getInt(TYPE_SIGN_IN_KEY);
                if (extraJson.has(TYPE_EMAIL_FROM_KEY))
                    from = extraJson.getString(TYPE_EMAIL_FROM_KEY);
                if (extraJson.has(TYPE_EMAIL_TITLE_KEY))
                    title = extraJson.getString(TYPE_EMAIL_TITLE_KEY);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        switch (msgType) {
            case TYPE_SIGN_IN:
                Intent intent = new Intent(context, SignInDialogAty.class);
                intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
                break;
            case TYPE_EMAIL:
                processEmailMsg(context, from, title, content);
                break;
            default:
        }
    }

    private void processEmailMsg(Context context, String from, String title, String content) {
        //将自定义信息存入数据库
        DatabaseHelper helper = OpenHelperManager.getHelper(context, DatabaseHelper.class);
        EmailBean bean = new EmailBean();
        bean.setFrom(from);
        bean.setTime(new Date());
        bean.setTitle(title);
        bean.setContent(content);
        bean.setReaded(false);
        helper.getEmailDao().create(bean);
        OpenHelperManager.releaseHelper();

        if (EmailListAty.isForeground) {
            Intent intent = new Intent(EmailListAty.EMAIL_RECEIVED_ACTION);
            context.sendBroadcast(intent);
        }

        if (SchoolInfoFragment.model != null)
            SchoolInfoFragment.model.updateCount();
    }

}
